//
//  XS_ExclusivePlanVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/4.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class XS_querySeriesCurriculumM: XS_BaseModel {
    var id = 0 // 课程编号
    var curriculumName = "" // 课程名称
    var isCertificate = "" // 是否带有证书 yes 是 no 否
    var curriculumImgUrl = "" // 课程图片地址
    var purchaseNum = 0 // 购买人数
    var chapterNum = 0 // 章节数量 步骤数
    var chapterSpecialDTOList: [XS_chapterSpecialDTOListM] = [] // 课程包含的章节集合
    var hourNum = "" // 课时数 共xx课时
    var price = "" // 原价
    var discountPrice = "" // 优惠价
    var vipPrice = "" // 会员价
    var vipIsFree = ""
    var isFree = ""
    var curriculumForm = "online"
}

class XS_ExclusivePlanVC: XS_BaseVC {
    typealias Section = SectionModel<String, XS_chapterSpecialDTOListM>
    
    lazy var industryId = 0
    
    override func upView() {
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "")?.withRenderingMode(.alwaysOriginal), style: .plain, target: nil, action: nil)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        title = "专属计划"
        view.backgroundColor = #colorLiteral(red: 0.8745098039, green: 0.9607843137, blue: 0.9411764706, alpha: 1)
        let imgV = UIImageView(image: UIImage(named: "编组 8备份 2"))
        view.addSubview(imgV)
        imgV.snp.makeConstraints { m in
            m.height.equalTo(.scale * 120)
            m.left.equalTo(.scale*16)
            m.right.equalTo(-.scale*16)
            m.top.equalTo(.scale*10)
        }
        
        let button = XS_NoHighlightBtn()
        button.setTitle("进入学习", for: .normal)
        button.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        button.titleLabel?.font = .xsFont(name: .medium, .scale*16)
        button.layer.cornerRadius = .scale*24
        button.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        view.addSubview(button)
        button.snp.makeConstraints { m in
            m.height.equalTo(.scale*48)
            m.bottom.equalTo(-.scale*32)
            m.left.equalTo(.scale*16)
            m.right.equalTo(-.scale*16)
        }
        button.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.navigationController?.popToRootViewController(animated: true)
            }).disposed(by: disposeBag)
        
        let scroll = UIScrollView()
        if #available(iOS 11.0, *) { scroll.contentInsetAdjustmentBehavior = .never }
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        scroll.bounces = false
        scroll.backgroundColor = UIColor.clear
        view.addSubview(scroll)
        scroll.snp.makeConstraints { m in
            m.left.right.equalToSuperview()
            m.top.equalTo(imgV.snp.bottom)
            m.bottom.equalTo(button.snp.top).offset(-.scale*20)
        }
        
        XS_NetWork.requestJson("/curriculum/querySeriesCurriculum", parameters: ["industryId":industryId])
            .mapModels(type: XS_querySeriesCurriculumM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self else { return }
                for (index, model) in models.enumerated() {
                    let item = self.getItem(model)
                    scroll.addSubview(item)
                    item.snp.makeConstraints { m in
                        m.width.equalTo(.scale*343)
                        m.height.equalTo(.scale*299)
                        m.left.equalTo(.scale*16)
                        m.top.equalTo(.scale*CGFloat(10+index*318))
                        m.bottom.lessThanOrEqualToSuperview().offset(-.scale*20)
                    }
                }
            }).disposed(by: disposeBag)
    }
    
    func getItem(_ item: XS_querySeriesCurriculumM) -> UIView {
        let view = UIView()
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                vc.id = "\(item.id)"
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        view.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
        let contentView = UIView()
        contentView.layer.cornerRadius = .scale*4
        contentView.layer.masksToBounds = true
        view.addSubview(contentView)
        contentView.snp.makeConstraints { $0.edges.equalToSuperview() }
        let imgV = UIImageView()
        imgV.contentMode = .scaleAspectFill
        imgV.clipsToBounds = true
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints { m in
            m.left.right.top.equalToSuperview()
            m.height.equalTo(.scale*128)
        }
        imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
        if item.isCertificate == "yes" {
            let icon = UIImageView(image: UIImage(named: "编组 39"))
            view.addSubview(icon)
            icon.snp.makeConstraints { m in
                m.width.equalTo(.scale*43)
                m.height.equalTo(.scale*49)
                m.top.equalTo(-.scale*5)
                m.right.equalTo(-.scale*10)
            }
        }
        
//        let nLab = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), text: item.curriculumName)
//        contentView.addSubview(nLab)
//        nLab.snp.makeConstraints { m in
//            m.left.top.equalTo(.scale*12)
//        }
        let cLab = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), text: "\(item.purchaseNum)人加入学习")
        contentView.addSubview(cLab)
        cLab.snp.makeConstraints { m in
            m.left.equalTo(.scale*12)
//            m.top.equalTo(nLab.snp.bottom).offset(.scale*6)
            m.bottom.equalTo(imgV.snp.bottom).offset(-.scale * 13)
        }
        let btn = XS_NoHighlightBtn()
        btn.layer.cornerRadius = .scale*12
        btn.layer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.19)
        btn.setTitle("  \(item.chapterNum)步骤 | \(item.hourNum)门课  ＞  ", for:.normal)
        btn.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .regular, .scale*12)
        contentView.addSubview(btn)
        btn.snp.makeConstraints { m in
            m.height.equalTo(.scale*23)
            m.right.equalTo(-.scale*12)
            m.bottom.equalTo(imgV.snp.bottom).offset(-.scale*13)
        }
        
        let buy = XS_NoHighlightBtn()
        buy.isUserInteractionEnabled = false
        buy.layer.cornerRadius = .scale*16
        buy.layer.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        buy.setTitle("立即购买", for: .normal)
        buy.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        buy.titleLabel?.font = .xsFont(name: .regular, .scale*13)
        contentView.addSubview(buy)
        buy.snp.makeConstraints { m in
            m.height.equalTo(.scale*32)
            m.width.equalTo(.scale*77)
            m.right.equalTo(-.scale*12)
            m.bottom.equalTo(-.scale*16)
        }
        buy.rx.tap.asDriver()
            .drive(onNext: {
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin(false)
                    return
                }
                let buyVC = XS_BuyVC()
                buyVC.courseId = "\(item.id)"
                buyVC.courseClassification = "online"
                XS_NVC.shared.pushViewController(buyVC, animated: true)
            }).disposed(by: disposeBag)
        
        let pLab = UILabel()
        contentView.addSubview(pLab)
        pLab.snp.makeConstraints { m in
            m.left.equalTo(.scale*12)
            m.bottom.equalTo(-.scale*16)
        }
        let (p, dp) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
        do {
            let text = NSMutableAttributedString()
            if p.count > 0 {
                let text1 = NSMutableAttributedString(string: "￥")
                text1.yy_font = .xsFont(name: .medium, .scale*14)
                text.append(text1)
            }
            let text2 = NSMutableAttributedString(string: p.count > 0 ? p : "免费")
            text2.yy_font = .xsFont(name: .semibold, .scale*18)
            text.append(text2)
            text.yy_color = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
            pLab.attributedText = text
        }
        
        let dLab = UILabel()
        contentView.addSubview(dLab)
        dLab.snp.makeConstraints { m in
            m.left.equalTo(pLab.snp.right).offset(.scale*4)
            m.centerY.equalTo(pLab.snp.centerY)
        }
        if dp.count > 0 {
            let text = NSMutableAttributedString(string: "原价\(dp)")
            text.yy_strikethroughStyle = .single
            text.yy_strikethroughColor = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.yy_font = .xsFont(name: .regular, .scale*12)
            dLab.attributedText = text
        }
        
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.itemSize = CGSize(width: .scale*164, height: .scale*95)
        flowLayout.minimumLineSpacing = .scale*12
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: .scale*12, bottom: 0, right: .scale*12)
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.bounces = false
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.backgroundColor = .clear
        contentView.addSubview(collection)
        collection.snp.makeConstraints { (m) in
            m.left.right.equalToSuperview()
            m.height.equalTo(.scale*96)
            m.top.equalTo(imgV.snp.bottom).offset(.scale*12)
        }
        
        collection.register(XS_ExclusivePlanCell.self, forCellWithReuseIdentifier: "cell")
        let dataSource = RxCollectionViewSectionedReloadDataSource<Section>(configureCell: { ds, cv, ip, it in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: ip) as! XS_ExclusivePlanCell
            cell.model.onNext(it)
            return cell
        })
        
        Driver.of([Section(model: "", items: item.chapterSpecialDTOList)])
            .drive(collection.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        collection.rx.modelSelected(String.self)
            .asDriver()
            .drive(onNext: { item in
                
            }).disposed(by: disposeBag)
        
        return view
    }
}

class XS_ExclusivePlanCell: XS_BaseCCell {
    lazy var model = PublishSubject<XS_chapterSpecialDTOListM>()
    
    override func upView() {
        layer.cornerRadius = .scale*4
        layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        
        let tLab = UILabel.xsLabel(size: .scale*12, fontName: .medium, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "01.基础入门")
        contentView.addSubview(tLab)
        tLab.snp.makeConstraints { (m) in
            m.left.equalTo(.scale*8)
            m.top.equalTo(.scale*9)
        }
        let nLab = UILabel()
        contentView.addSubview(nLab)
        nLab.snp.makeConstraints { (m) in
            m.left.equalTo(.scale*8)
            m.top.equalTo(.scale*30)
            m.right.lessThanOrEqualTo(-.scale*6)
        }
        nLab.numberOfLines = 0
        let text = NSMutableAttributedString(string: "课程名称课程名称课程名称")
        text.yy_font = .xsFont(name: .medium, .scale*14)
        text.yy_color = #colorLiteral(red: 0.1607843137, green: 0.1647058824, blue: 0.168627451, alpha: 1)
        nLab.attributedText = text
        
        let cLab = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "共9节")
        contentView.addSubview(cLab)
        cLab.snp.makeConstraints { (m) in
            m.left.equalTo(.scale*11)
            m.bottom.equalTo(-.scale*3)
        }
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = CGRect(x: .scale*123, y: .scale*77, width: .scale*41, height: .scale*18)
        let maskPath = UIBezierPath(roundedRect: shapeLayer.bounds, byRoundingCorners: [.topLeft, .bottomRight], cornerRadii: CGSize(width: .scale*4, height: .scale*4))
        shapeLayer.path = maskPath.cgPath
        shapeLayer.fillColor = #colorLiteral(red: 0.831372549, green: 0.9490196078, blue: 0.9215686275, alpha: 1)
        contentView.layer.addSublayer(shapeLayer)
        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1), text: "可试看")
        contentView.addSubview(label)
        label.snp.makeConstraints { maker in
            maker.centerX.equalTo(.scale*144)
            maker.centerY.equalTo(.scale*86)
        }
//        icon_24px_播放_1
        let lock = UIImageView(image: UIImage(named: "icon_24px_播放_1"))
        contentView.addSubview(lock)
        lock.snp.makeConstraints({
            $0.width.height.equalTo(.scale*15)
            $0.bottom.equalTo(-.scale*5)
            $0.right.equalTo(-.scale*10)
        })
        
        model.subscribe(onNext: { item in
            tLab.text = item.chapterName
            nLab.text = item.curriculumHourName
            cLab.text = "共\(item.count)节"
            let set = item.isWatch == "yes"
            shapeLayer.isHidden = !set
            label.isHidden = !set
            lock.isHidden = set
        }).disposed(by: disposeBag)
    }
}
